package com.czk.classreader.method;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;

import java.util.Objects;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/6 16:34
 */
public abstract class ClassAddMethodVisitor extends ClassVisitor {
    private final int methodAccess;
    private final String methodName;
    private final String methodDesc;
    private final String methodSignature;
    private final String[] methodExceptions;
    private boolean isMethodPresent;

    public ClassAddMethodVisitor(int api, ClassVisitor classVisitor, int methodAccess, String methodName, String methodDesc, String methodSignature, String[] methodExceptions) {
        super(api, classVisitor);
        this.methodAccess = methodAccess;
        this.methodName = methodName;
        this.methodDesc = methodDesc;
        this.methodSignature = methodSignature;
        this.methodExceptions = methodExceptions;
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        if (Objects.equals(name, methodName) && Objects.equals(methodDesc, descriptor)) {
            isMethodPresent = true;
        }
        return super.visitMethod(access, name, descriptor, signature, exceptions);
    }

    @Override
    public void visitEnd() {
        if (!isMethodPresent) {
            MethodVisitor methodVisitor = super.visitMethod(methodAccess, methodName, methodDesc, methodSignature, methodExceptions);
            if (methodVisitor != null) {
                generateMethodBody(methodVisitor);
            }
        }
        super.visitEnd();
    }

    /**
     * 实现抽象方法
     * 自己实现方法体
     *
     * @param methodVisitor
     */
    public abstract void generateMethodBody(MethodVisitor methodVisitor);
}
